package cn.iocoder.yudao.module.xkfz.service.clinicalHealthCare.impl;


import cn.iocoder.yudao.module.xkfz.domain.dto.ElementDataMonthXkrcDto;
import cn.iocoder.yudao.module.xkfz.domain.excel.entity.*;
import cn.iocoder.yudao.module.xkfz.mapper.excel.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.module.xkfz.mapper.clinicalHealthCare.ElementDataMonthXkrcMapper;
import cn.iocoder.yudao.module.xkfz.domain.entity.clinicalHealthCare.ElementDataMonthXkrc;
import cn.iocoder.yudao.module.xkfz.service.clinicalHealthCare.ElementDataMonthXkrcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (ElementDataMonthXkrc)表服务实现类
 *
 * @author wangzx
 * @since 2024-11-08 10:13:54
 */
@Service("elementDataMonthXkrcService")
public class ElementDataMonthXkrcServiceImpl extends ServiceImpl<ElementDataMonthXkrcMapper, ElementDataMonthXkrc> implements ElementDataMonthXkrcService {
    @Autowired
    private ElementDataMonthXkrcMapper elementDataMonthXkrcMapper;
    @Autowired
    private AchievementAwardMapper achievementAwardMapper;
    @Autowired
    private GuidelinesAndConsensusMapper guidelinesAndConsensusMapper;
    @Autowired
    private InventionPatentMapper inventionPatentMapper;
    @Autowired
    private LeadMulticenterProjectsMapper leadMulticenterProjectsMapper;
    @Autowired
    private PatentTransferMapper patentTransferMapper;
    @Autowired
    private ProjectInfoMapper projectInfoMapper;
    @Autowired
    private StandardMapper standardMapper;
    @Autowired
    private TechnologicalOutputSciMapper technologicalOutputSciMapper;

    @Override
    public List<ElementDataMonthXkrcDto> listCmi() {
        return elementDataMonthXkrcMapper.listCmi();
    }

    @Override
    public List<ElementDataMonthXkrcDto> listFourOperation() {
        return Collections.emptyList();
    }

    @Override
    public HashMap<String, Object> listKjc(String deptName) {
        // 查询指南与共识
        QueryWrapper<GuidelinesAndConsensus> guidelinesAndConsensusWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            guidelinesAndConsensusWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<GuidelinesAndConsensus> guidelinesAndConsensuses = guidelinesAndConsensusMapper.selectList(guidelinesAndConsensusWrapper);

        // 查询专利
        QueryWrapper<InventionPatent> inventionPatentWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            inventionPatentWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<InventionPatent> inventionPatents = inventionPatentMapper.selectList(inventionPatentWrapper);

        // 查询牵头多中心
        QueryWrapper<LeadMulticenterProjects> leadMulticenterProjectsWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            leadMulticenterProjectsWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<LeadMulticenterProjects> leadMulticenterProjects = leadMulticenterProjectsMapper.selectList(leadMulticenterProjectsWrapper);

        // 查询专利转换
        QueryWrapper<PatentTransfer> patentTransferWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            patentTransferWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<PatentTransfer> patentTransfers = patentTransferMapper.selectList(patentTransferWrapper);

        // 查询课题信息表
        QueryWrapper<ProjectInfo> projectInfoWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            projectInfoWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<ProjectInfo> projectInfos = projectInfoMapper.selectList(projectInfoWrapper);

        // 查询南大SCI
        QueryWrapper<TechnologicalOutputSci> technologicalOutputSciWrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            technologicalOutputSciWrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        List<TechnologicalOutputSci> technologicalOutputScis = technologicalOutputSciMapper.selectList(technologicalOutputSciWrapper);

// 查询指南与共识并获取前五和后五
        QueryWrapper<GuidelinesAndConsensus> qwTop5 = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            qwTop5.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        qwTop5.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> top5List = guidelinesAndConsensusMapper.selectMaps(qwTop5)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<GuidelinesAndConsensus> qwBottom5 = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            qwBottom5.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        qwBottom5.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> bottom5List = guidelinesAndConsensusMapper.selectMaps(qwBottom5)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

// 查询专利并获取前五和后五
        QueryWrapper<InventionPatent> patentTop5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            patentTop5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        patentTop5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> patentTop5 = inventionPatentMapper.selectMaps(patentTop5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<InventionPatent> patentBottom5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            patentBottom5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        patentBottom5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> patentBottom5 = inventionPatentMapper.selectMaps(patentBottom5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

// 查询牵头多中心并获取前五和后五
        QueryWrapper<LeadMulticenterProjects> leadTop5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            leadTop5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        leadTop5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> leadTop5 = leadMulticenterProjectsMapper.selectMaps(leadTop5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<LeadMulticenterProjects> leadBottom5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            leadBottom5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        leadBottom5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> leadBottom5 = leadMulticenterProjectsMapper.selectMaps(leadBottom5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

// 查询专利转换并获取前五和后五
        QueryWrapper<PatentTransfer> transferTop5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            transferTop5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        transferTop5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> transferTop5 = patentTransferMapper.selectMaps(transferTop5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<PatentTransfer> transferBottom5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            transferBottom5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        transferBottom5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> transferBottom5 = patentTransferMapper.selectMaps(transferBottom5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

// 查询课题信息并获取前五和后五
        QueryWrapper<ProjectInfo> projectTop5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            projectTop5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        projectTop5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> projectTop5 = projectInfoMapper.selectMaps(projectTop5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<ProjectInfo> projectBottom5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            projectBottom5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        projectBottom5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> projectBottom5 = projectInfoMapper.selectMaps(projectBottom5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

// 查询南大SCI并获取前五和后五
        QueryWrapper<TechnologicalOutputSci> sciTop5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            sciTop5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        sciTop5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByDesc("count");  // 按 count 倒序排列
        List<Map<String, Object>> sciTop5 = technologicalOutputSciMapper.selectMaps(sciTop5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取前5条

        QueryWrapper<TechnologicalOutputSci> sciBottom5Wrapper = new QueryWrapper<>();
        if (deptName != null && !deptName.isEmpty()) {
            sciBottom5Wrapper.like("dept_name", deptName);  // 使用like进行模糊查询
        }
        sciBottom5Wrapper.select("dept_name AS deptName", "COUNT(*) AS count")
                .groupBy("dept_name")
                .orderByAsc("count");  // 按 count 正序排列
        List<Map<String, Object>> sciBottom5 = technologicalOutputSciMapper.selectMaps(sciBottom5Wrapper)
                .stream().limit(5).map(map -> map.entrySet().stream()
                        .collect(Collectors.toMap(
                                entry -> entry.getKey().toUpperCase(), // 键转为大写
                                Map.Entry::getValue // 值保持不变
                        ))).collect(Collectors.toList());  // 只取后5条

        // 分别计算每个列表的统计信息
        Map<String, Object> guidelinesAndConsensusStats = calculateDeptStats(guidelinesAndConsensuses, GuidelinesAndConsensus::getDeptName);
        Map<String, Object> inventionPatentsStats = calculateDeptStats(inventionPatents, InventionPatent::getDeptName);
        Map<String, Object> leadMulticenterProjectsStats = calculateDeptStats(leadMulticenterProjects, LeadMulticenterProjects::getDeptName);
        Map<String, Object> patentTransfersStats = calculateDeptStats(patentTransfers, PatentTransfer::getDeptName);
        Map<String, Object> projectInfosStats = calculateDeptStats(projectInfos, ProjectInfo::getDeptName);
        Map<String, Object> technologicalOutputScisStats = calculateDeptStats(technologicalOutputScis, TechnologicalOutputSci::getDeptName);


        // 将结果放入结果集
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("guidelinesAndConsensuses", guidelinesAndConsensuses);
        resultMap.put("inventionPatents", inventionPatents);
        resultMap.put("leadMulticenterProjects", leadMulticenterProjects);
        resultMap.put("patentTransfers", patentTransfers);
        resultMap.put("projectInfos", projectInfos);
        resultMap.put("technologicalOutputScis", technologicalOutputScis);

        resultMap.put("top5GuidelinesAndConsensus", top5List);
        resultMap.put("bottom5GuidelinesAndConsensus", bottom5List);
        resultMap.put("top5InventionPatents", patentTop5);
        resultMap.put("bottom5InventionPatents", patentBottom5);
        resultMap.put("top5LeadMulticenterProjects", leadTop5);
        resultMap.put("bottom5LeadMulticenterProjects", leadBottom5);
        resultMap.put("top5PatentTransfers", transferTop5);
        resultMap.put("bottom5PatentTransfers", transferBottom5);
        resultMap.put("top5ProjectInfos", projectTop5);
        resultMap.put("bottom5ProjectInfos", projectBottom5);
        resultMap.put("top5TechnologicalOutputScis", sciTop5);
        resultMap.put("bottom5TechnologicalOutputScis", sciBottom5);

        // 将每个查询表的统计信息放入结果集
        resultMap.put("guidelinesAndConsensusStats", guidelinesAndConsensusStats);
        resultMap.put("inventionPatentsStats", inventionPatentsStats);
        resultMap.put("leadMulticenterProjectsStats", leadMulticenterProjectsStats);
        resultMap.put("patentTransfersStats", patentTransfersStats);
        resultMap.put("projectInfosStats", projectInfosStats);
        resultMap.put("technologicalOutputScisStats", technologicalOutputScisStats);
        return resultMap;
    }

//    // 计算全部均分、最高科室、最低科室的通用方法
//    public Map<String, Object> calculateDeptStats(List<Map<String, Object>> deptData) {
//        // 计算全部均分
//        int totalCount = deptData.stream().mapToInt(item -> Integer.parseInt(item.get("COUNT").toString())).sum();
//        int totalDepts = deptData.size();
//        double avgDeptCount = totalDepts == 0 ? 0 : (double) totalCount / totalDepts;
//
//        // 计算总数
//        int totalRecords = totalCount;
//
//        // 计算最高科室（记录数最多的科室数量）
//        int maxDeptCount = deptData.stream()
//                .mapToInt(item -> Integer.parseInt(item.get("COUNT").toString()))
//                .max()
//                .orElse(0);  // 如果没有数据，返回0
//
//        // 计算最低科室（记录数最少的科室数量）
//        int minDeptCount = deptData.stream()
//                .mapToInt(item -> Integer.parseInt(item.get("COUNT").toString()))
//                .min()
//                .orElse(0);  // 如果没有数据，返回0
//
//        // 将计算结果返回
//        Map<String, Object> stats = new HashMap<>();
//        stats.put("avgDeptCount", avgDeptCount);   // 全部均分
//        stats.put("totalRecords", totalRecords);   // 总数
//        stats.put("maxDeptCount", maxDeptCount);   // 最高科室的数量
//        stats.put("minDeptCount", minDeptCount);   // 最低科室的数量
//
//        return stats;
//    }

    // 通用统计方法，适用于任意包含部门字段的 List<T>
    public <T> Map<String, Object> calculateDeptStats(List<T> list, Function<T, String> deptExtractor) {
        // 如果列表为空或deptExtractor为空，直接返回默认值
        if (list == null || list.isEmpty() || deptExtractor == null) {
            Map<String, Object> defaultStats = new HashMap<>();
            defaultStats.put("avgDeptCount", "0.00"); // 平均值保留两位小数
            defaultStats.put("totalRecords", 0);     // 总数
            defaultStats.put("maxDeptCount", 0);     // 最大值
            defaultStats.put("minDeptCount", 0);     // 最小值
            return defaultStats;
        }

        // 使用 Map 按科室分组统计，将空值统一归类为 "未分配"
        Map<String, Long> deptCounts = list.stream()
                .collect(Collectors.groupingBy(
                        item -> {
                            String deptName = deptExtractor.apply(item);
                            return (deptName == null || deptName.isEmpty()) ? "未分配" : deptName;
                        },
                        Collectors.counting()
                ));

        // 计算总记录数
        int totalRecords = list.size();

        // 计算最高科室（记录数最多的科室数量）
        int maxDeptCount = deptCounts.values().stream()
                .mapToInt(Long::intValue)
                .max()
                .orElse(0);

        // 计算最低科室（记录数最少的科室数量）
        int minDeptCount = deptCounts.values().stream()
                .mapToInt(Long::intValue)
                .min()
                .orElse(0);

        // 计算平均值，保留两位小数
        double avgDeptCount = deptCounts.isEmpty() ? 0 : (double) totalRecords / deptCounts.size();
        String formattedAvgDeptCount = String.format("%.2f", avgDeptCount);

        // 返回统计结果
        Map<String, Object> stats = new HashMap<>();
        stats.put("avgDeptCount", formattedAvgDeptCount); // 平均值
        stats.put("totalRecords", totalRecords);         // 总记录数
        stats.put("maxDeptCount", maxDeptCount);         // 最大值
        stats.put("minDeptCount", minDeptCount);         // 最小值

        return stats;
    }


}

